#!/bin/bash
echo "🚀 启动MES系统..."
echo "时间: $(date)"
echo ""

# 停止现有服务
echo "1. 停止现有服务..."
pkill -f "python manage.py runserver" 2>/dev/null
sleep 3

# 清理日志
echo "2. 清理日志..."
rm -f /tmp/mes_final_*.log

# 启动服务
echo "3. 启动服务..."
echo "   - 启动基础服务 (端口8000)..."
nohup python manage.py runserver 0.0.0.0:8000 --settings=settings_simple > /tmp/mes_final_8000.log 2>&1 &
sleep 2

echo "   - 启动服务1 (端口8001)..."
nohup python manage.py runserver 0.0.0.0:8001 --settings=settings_simple > /tmp/mes_final_8001.log 2>&1 &
sleep 2

echo "   - 启动服务2 (端口8002)..."
nohup python manage.py runserver 0.0.0.0:8002 --settings=settings_simple > /tmp/mes_final_8002.log 2>&1 &
sleep 2

echo "   - 启动服务3 (端口8003)..."
nohup python manage.py runserver 0.0.0.0:8003 --settings=settings_simple > /tmp/mes_final_8003.log 2>&1 &
sleep 2

# 等待服务启动
echo "4. 等待服务启动..."
sleep 5

# 检查服务状态
echo "5. 检查服务状态..."
for port in 8000 8001 8002 8003; do
    status=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:$port/admin/ 2>/dev/null)
    if [ "$status" = "302" ] || [ "$status" = "200" ]; then
        echo "   ✅ 端口 $port: 正常 (HTTP $status)"
    else
        echo "   ❌ 端口 $port: 异常 (HTTP $status)"
    fi
done

echo ""
echo "🎉 MES系统启动完成！"
echo ""
echo "📋 访问地址:"
echo "   - 主服务: http://175.27.138.86:8000/admin/"
echo "   - 服务1: http://175.27.138.86:8001/admin/"
echo "   - 服务2: http://175.27.138.86:8002/admin/"
echo "   - 服务3: http://175.27.138.86:8003/admin/"
echo ""
echo "🔑 登录信息:"
echo "   - 用户名: admin"
echo "   - 密码: admin123"
echo ""
echo "📊 查看日志:"
echo "   - tail -f /tmp/mes_final_8000.log"
echo "   - tail -f /tmp/mes_final_8001.log"
echo "   - tail -f /tmp/mes_final_8002.log"
echo "   - tail -f /tmp/mes_final_8003.log"
echo ""
echo "🛑 停止服务:"
echo "   - pkill -f 'python manage.py runserver'"
echo ""
echo "📈 运行进程:"
ps aux | grep "python manage.py runserver" | grep -v grep 